﻿using Microsoft.AspNetCore.Http;
using PlayingCards.Model.Entity;
using PlayingCards.Repository.BaseRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace PlayingCards.Service.TokenService
{
    /// <summary>
    /// 
    /// </summary>
    public class UserTokenService : IUserTokenService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly BaseRepository<Player> _player;
        public UserTokenService(IHttpContextAccessor httpContextAccessor , BaseRepository<Player> player)
        {
            _httpContextAccessor = httpContextAccessor;
            _player = player;
        }
        private HttpContext GetHttpContext()
        {
            return _httpContextAccessor.HttpContext;
        }

        /// <summary>
        /// 查询有效载荷中的openid
        /// </summary>
        /// <returns></returns>
        private string GetOpenId()
        {
            //foreach (var claim in GetHttpContext().User.Claims)
            //{
            //    Console.WriteLine($"{claim.Type}: {claim.Value}");
            //}
            var user = GetHttpContext().User.FindFirst(e => e.Type == ClaimTypes.Name)?.Value;
            
            return user;
        }

        /// <summary>
        ///  获取当前登录的用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<Player> GetUser()
        {
            var openid = GetOpenId();
            var model = await _player.AsQueryable().FirstAsync(e => e.OpenId == openid);
            return model;
        }

        /// <summary>
        /// 获取当前登录的用户id
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetUserId()
        {
            var openid = GetOpenId();
            var model = await _player.AsQueryable().Select(e => new { e.Id, e.OpenId }).FirstAsync(e => e.OpenId == openid);
            return model.Id;
        }
    }
}
